package org.lzy.shop.base

import ExceptionHandler.handleException
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.viewbinding.ViewBinding
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.launch
import org.lzy.shop.R
import org.lzy.shop.theme.ThemeManager
import org.lzy.shop.util.ToastUtil

/**
 * 使用ViewBinding的基础Fragment
 * @param VB 视图绑定类型
 * @param inflate 视图绑定的膨胀函数
 */
abstract class BaseFragment<VB : ViewBinding>(
    private val inflate: (LayoutInflater, ViewGroup?, Boolean) -> VB
) : Fragment() {

    // 添加日志标签
    private val TAG: String = this.javaClass.simpleName

    // 视图绑定 - 使用可空类型并在onDestroyView中清理
    private var _binding: VB? = null
    protected val binding: VB
        get() = requireNotNull(_binding) { "ViewBinding已被销毁，请确保在onViewCreated之后使用" }

    // 使用requireContext()和requireActivity()代替自定义的mContext引用
    // 移除可能导致内存泄漏的mContext引用

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // 初始化视图绑定
        _binding = inflate(inflater, container, false)

        // 从保存的状态恢复数据
        savedInstanceState?.getBundle("savedState")?.let {
            onRestoreState(it)
        }

        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // 初始化视图
        initView()

        // 初始化主题
        ThemeManager.init(requireActivity())

        //请求后台返回数据统一在这个方法调用
        requestData()

        // 初始化点击事件
        allClick()

        // 初始化数据观察
        initData()
    }

    // LiveData扩展函数 - 自动适配不同场景
    fun <T> LiveData<T>.observeWithLifecycle(
        owner: LifecycleOwner,
        state: Lifecycle.State = Lifecycle.State.STARTED,
        observer: Observer<T>
    ) {
        owner.lifecycleScope.launch {
            repeatOnLifecycle(state) {
                observe(owner, observer)
            }
        }
    }

    // 简化版（默认STARTED状态）
    fun <T> LiveData<T>.observeSimplified(owner: LifecycleOwner, observer: Observer<T>) {
        observe(owner, observer)
    }

    /**
     * 初始化视图，子类实现
     */
    protected abstract fun initView()

    /**
     * 请求后台返回数据统一在这个方法调用
     */
    protected abstract fun requestData()

    /**
     * 初始化或加载数据，例如发起网络请求后回调
     */
    protected abstract fun initData()

    /**
     * 初始化点击事件，子类实现
     */
    protected abstract fun allClick()



    /**
     * 带请求码启动Activity用于接收结果
     * @param clazz 目标Activity类
     * @param requestCode 请求码
     */
    fun startActivityForResult(clazz: Class<*>, requestCode: Int) {
        startActivityForResult(Intent(requireContext(), clazz), requestCode)
    }

    /**
     * 带Bundle数据和请求码启动Activity用于接收结果
     * @param clazz 目标Activity类
     * @param bundle 传递的数据
     * @param requestCode 请求码
     */
    fun startActivityForResult(clazz: Class<*>, bundle: Bundle, requestCode: Int) {
        startActivityForResult(Intent(requireContext(), clazz).apply {
            putExtras(bundle)
        }, requestCode)
    }

    /**
     * 启动新的Activity
     * @param clazz 目标Activity类
     * @param options Activity转场动画选项
     */
    fun startActivity(clazz: Class<*>?) {
        startActivity(Intent(requireContext(), clazz))
    }

    /**
     * 启动新的Activity并结束当前Activity
     * @param clazz 目标Activity类
     * @param options Activity转场动画选项
     */
    fun startKillActivity(clazz: Class<*>?) {
        startActivity(Intent(requireContext(), clazz))
        requireActivity().finish()
    }

    /**
     * 带Bundle数据启动新的Activity
     * @param clazz 目标Activity类
     * @param bundle 传递的数据
     */
    fun startActivity(clazz: Class<*>, bundle: Bundle) {
        startActivity(Intent(requireContext(), clazz).apply {
            putExtras(bundle)
        })
    }

    /**
     * 带Bundle数据启动新的Activity并结束当前Activity
     * @param clazz 目标Activity类
     * @param bundle 传递的数据
     */
    fun startKillActivity(clazz: Class<*>, bundle: Bundle) {
        startActivity(Intent(requireContext(), clazz).apply {
            putExtras(bundle)
        })
        requireActivity().finish()
    }



    //设置文本
    fun getResString(resid: Int): String {
        return getString(resid)
    }

    /**
     * 保存Fragment状态
     */
    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)

        // 创建保存状态的Bundle
        val state = Bundle()
        // 让子类保存自己的状态
        onSaveState(state)
        outState.putBundle("savedState", state)
    }

    /**
     * 子类实现此方法保存状态
     */
    protected open fun onSaveState(bundle: Bundle) {
        // 子类重写此方法保存自己的状态
    }

    /**
     * 子类实现此方法恢复状态
     */
    protected open fun onRestoreState(bundle: Bundle) {
        // 子类重写此方法恢复自己的状态
    }

    //设置文字颜色
    fun getResColor(resid: Int): Int {
        return ContextCompat.getColor(requireContext(), resid)
    }

    //显示等待对话框
    fun showLoadingDialog() {
        try {
            (requireActivity() as? BaseActivity<*>)?.showLoading()
        } catch (e: ClassCastException) {
            e.printStackTrace()
        }
    }

    //关闭对话框
    fun dismissLoadingDialog() {
        try {
            (requireActivity() as? BaseActivity<*>)?.dismissLoading()
        } catch (e: ClassCastException) {
            e.printStackTrace()
        }
    }

    // 安全地执行协程，自动处理异常
    protected fun safeLaunch(block: suspend () -> Unit) {
        lifecycleScope.launch(CoroutineExceptionHandler { _, throwable ->
            handleException(throwable)
        }) {
            block()
        }
    }

    fun showToast(msg: String?) {
        ToastUtil.show(msg)
    }

    // 添加成功Toast方法
    fun showSuccessToast(msg: String) {
        ToastUtil.showSuccess(msg)
    }

    // 添加错误Toast方法
    fun showErrorToast(msg: String) {
        ToastUtil.showError(msg)
    }

    protected fun showEmptyView(): View? {
        return LayoutInflater.from(requireContext()).inflate(R.layout.empty_view, null)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        // 清理ViewBinding引用，防止内存泄漏
        _binding = null
    }


}